﻿@page "/System/SysDictType"

@namespace SageKing.Studio.Pages.DictType

@implements IMenuTab<SysMenu, long>
@implements IReuseTabsPage

@inject IMessageService _message
@inject IConfirmService _confirmService

@using SageKing.Studio.Pages.DictType.component

<PageTitle>@TabTitle</PageTitle>

@inject SysDictTypeService dataService
@inject SysDictDataService dataChildService
@inject SysMenuService _menuService

@if (pageData == null)
{
	<Spin size="SpinSize.Large" Tip="Loading..." />
}
else
{
	<Table @ref="table" TItem="SysDictType" DataSource="@pageData.Items" OnExpand="OnRowExpand" OnRowClick="OnRowClick"
		   RowKey="x=>x.Id" Size="TableSize.Small"
		   Loading="tableLoading"
		   @bind-SelectedRows="@selectedRows" Resizable Bordered EnableVirtualization
		   Class="main-table" ScrollY="@BrowserConsts.ScrollYTable" PageSize="pageData.PageSize">

		<TitleTemplate>
			<Space>
				<SpaceItem>
					<Search Placeholder="名称" @bind-Value="searchModel.Name" OnSearch="async () => { await OnSearch(pageargs); Message(); }" AllowClear="true" />
				</SpaceItem>

				<SpaceItem>
					<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Reload" OnClick="() => ReSet()">重置</Button>
				</SpaceItem>

				<SpaceItem>
					<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.AppstoreAdd" OnClick="() => dictTypeEditModal.MeCrud.ShowAdd(0, true)">新增</Button>
				</SpaceItem>
			</Space>
		</TitleTemplate>
		<ColumnDefinitions>
			<Selection Type="@selectionType"></Selection>
			<PropertyColumn Property="c => c.Name" Title="名称" Sortable="true" Filterable />
			<PropertyColumn Property="c => c.Type" Title="字典类型" Align="ColumnAlign.Center" Sortable="true" Filterable />
			<PropertyColumn Property="c => c.Code" Title="编码" Sortable="true" Filterable />
			<PropertyColumn Property="c => c.Status" Title="状态" Align="ColumnAlign.Center" Sortable="true" Filterable>
				<Switch @bind-Value="@context.Status" OnClick="() => dictTypeEditModal.EditOnStatusSwitch(context)" CheckedChildren="开" UnCheckedChildren="关"></Switch>
			</PropertyColumn>
			<PropertyColumn Property="c => c.OrderNo" Title="排序" Align="ColumnAlign.Center" Sortable="true" Filterable>
			</PropertyColumn>
			<PropertyColumn Property="c => c.Remark" Title="备注" Ellipsis />
			<PropertyColumn Property="c => c.Id" Title="Id" Sortable="true" Filterable />
			<PropertyColumn Title="时间相关" Property="c => c.CreateUserName" Align="ColumnAlign.Center">
				<Popover ContentTemplate="@baseRender.GetDetails(context)" Title="时间相关">
					<Button Icon="@IconType.Outline.OrderedList" Shape="@ButtonShape.Circle" />
				</Popover>
			</PropertyColumn>
			<ActionColumn Title="Action" Fixed="ColumnFixPlacement.Right">
				<Space>
					<SpaceItem>
						<Tooltip Title="@IconType.Outline.Edit">
							<Button OnClick="(e) => dictTypeEditModal.MeCrud.ShowEdit(context)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Edit" />
						</Tooltip>
					</SpaceItem>
					<SpaceItem>
						<Popconfirm Title="确认删除?"
									OnConfirm="(e) => dictTypeEditModal.DeleteData(context)"
									OkText="Yes"
									CancelText="No">
							<Button Icon="@IconType.Outline.Delete" Shape="@ButtonShape.Circle" Danger></Button>
						</Popconfirm>
					</SpaceItem>
				</Space>
			</ActionColumn>
		</ColumnDefinitions>

		<ExpandTemplate Context="rowData">
			<Table Class="childTable" TItem="SysDictData" DataSource="rowData.Data.Children" Loading="rowData.Data.Children == null" Size=@TableSize.Small EnableVirtualization PageSize="10" ScrollY="200px" PaginationPosition="bottomCenter"
				   @bind-SelectedRows="@selectedRowsChild" RowKey="a => a.Id.ToString()" Resizable Bordered>
				<TitleTemplate>
					<Space>
						<SpaceItem>
							<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.AppstoreAdd" OnClick="(e) => dictDataEditModal.MeCrud.ShowAdd(rowData.Data, false)">新增字典值</Button>
						</SpaceItem>
					</Space>

				</TitleTemplate>
				<ColumnDefinitions>
					<Selection Key="@rowData.Data.Id.ToString()" Type="@selectionType"></Selection>
					<PropertyColumn Property="c => c.Name" Title="名称" Sortable="true" Filterable />
					<PropertyColumn Property="c => c.Code" Title="编码" Sortable="true" Filterable />
					<PropertyColumn Property="c => c.Status" Title="Status" Sortable="true" Align="ColumnAlign.Center" Filterable>
						<Switch @bind-Value="@context.Status" OnClick="() => dictDataEditModal.EditOnStatusSwitch(context)" CheckedChildren="开" UnCheckedChildren="关"></Switch>
					</PropertyColumn>
					<PropertyColumn Property="c => c.Value" Title="值" Ellipsis />
					<PropertyColumn Property="c => c.ValueInt" Title="值Int"></PropertyColumn>
					<PropertyColumn Property="c => c.Id" Title="Id" Sortable="true" Filterable />
					<PropertyColumn Title="时间相关" Property="c => c.CreateUserName" Align="ColumnAlign.Center">
						<Popover ContentTemplate="@baseRender.GetDetails(context)" Title="时间相关">
							<Button Icon="@IconType.Outline.OrderedList" Shape="@ButtonShape.Circle" />
						</Popover>
					</PropertyColumn>
					<ActionColumn Title="Action" Fixed="ColumnFixPlacement.Right">
						<Space>
							<SpaceItem>
								<Tooltip Title="@IconType.Outline.Edit">
									<Button OnClick="
					(e) =>
				{
					dictDataEditModal.ParentName = rowData.Data.Name;
					dictDataEditModal.isDB = rowData.Data.Type;
					dictDataEditModal.MeCrud.ShowEdit(context);
				}"
										Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Edit" />
							</Tooltip>
						</SpaceItem>
						<SpaceItem>
							<Popconfirm Title="确认删除?"
										OnConfirm="() => dictDataEditModal.DeleteData(context,rowData.Data)"
										OkText="Yes"
										CancelText="No">
								<Button Icon="@IconType.Outline.Delete" Shape="@ButtonShape.Circle" Danger></Button>
							</Popconfirm>

						</SpaceItem>
					</Space>
				</ActionColumn>
			</ColumnDefinitions>
			<PaginationTemplate>
				<Pagination Class="@(context.PaginationClass + " my-custom-pagination")"
							Total="context.Total"
							ShowTotal="showTotal"
							PageSize="context.PageSize"
							Current="context.PageIndex"
							ShowSizeChanger
							OnChange="context.HandlePageChange" />
			</PaginationTemplate>
		</Table>
	</ExpandTemplate>
	<PaginationTemplate>
		<Pagination ShowTotal="showTotal" Class="@(context.PaginationClass + " my-custom-pagination")"
					Total="pageData.Total"
					PageSize="pageData.PageSize"
					Current="pageData.Page"
					ShowSizeChanger
					ShowQuickJumper
					OnChange="OnSearch" />
	</PaginationTemplate>
</Table>

<Modal Title="@dictTypeEditModal.Title" Class="modelDefault" Resizable="@true" MaxBodyHeight="@("65vh")"
	   @bind-Visible="@dictTypeEditModal.Visible" Draggable="true" Centered Closable="false"
	   OnOk="dictTypeEditModal.HandleOk" ConfirmLoading="dictTypeEditModal.Loading" OkText="dictTypeEditModal.OkTitle" CancelText="dictTypeEditModal.CancelText">

	@dictTypeEditModal.ModalTemplate
</Modal>

<Modal Title="@dictDataEditModal.Title" Class="modelDefault" Resizable="@true" MaxBodyHeight="@("65vh")"
	   @bind-Visible="@dictDataEditModal.Visible" Draggable="true" Centered Closable="false"
	   OnOk="dictDataEditModal.HandleOk" ConfirmLoading="dictDataEditModal.Loading" OkText="dictDataEditModal.OkTitle" CancelText="dictDataEditModal.CancelText">

	@dictDataEditModal.ModalTemplate
</Modal>
}



@code {

	//主表
	[Inject]
	DictTypeEditModal dictTypeEditModal { get; set; }

	void InitDictTypeEditModal()
	{
		dictTypeEditModal.Error = Error;

		dictTypeEditModal.TabTitle = TabTitle;

		dictTypeEditModal.ModalTemplate = @<DictTypeEdit @ref=@dictTypeEditModal.Component Title="@dictTypeEditModal.Title" model="@dictTypeEditModal.Model"></DictTypeEdit>;

		dictTypeEditModal.RefreshFunc = Refresh;
		dictTypeEditModal.ResetDataAction = () =>
		{
			table?.ResetData();
		};
		dictTypeEditModal.StateHasChanged = StateHasChanged;
	}
}

@code {

	//明细表
	[Inject]
	DictDataEditModal dictDataEditModal { get; set; }

	void InitDictDataEditModal()
	{
		dictDataEditModal.Error = Error;

		dictDataEditModal.TabTitle = TabTitle + "->字典值";

		dictDataEditModal.ModalTemplate = @<DictDataEdit @ref="@dictDataEditModal.Component" IsDB="@dictDataEditModal.isDB" model="@dictDataEditModal.Model"></DictDataEdit>;

		dictDataEditModal.QueryChildListFunc = QueryChildList;
		dictDataEditModal.StateHasChanged = StateHasChanged;
	}

}

@code {

	bool loading;
	bool IsfirstRender = false;

	BaseRenderFragment baseRender;

	//table
	ITable table;
	bool tableLoading;
	SelectionType selectionType = SelectionType.Checkbox;
	bool isOnRowExpand = false;
	RenderFragment<PaginationTotalContext> showTotal = ctx => @<div class="showTotal">Total: <b>@ctx.Total</b></div>;

	//search
	SysDictType searchModel;

	PaginationEventArgs pageargs = new PaginationEventArgs(1, 10);
	PageBase<SysDictType> pageData;

	IEnumerable<SysDictType> selectedRows;
	IEnumerable<SysDictData> selectedRowsChild;

	#region menu
	public IMenuTab<SysMenu, long> MeTab { get { return this; } }

	public IBaseServiceCache<SysMenu, long> MenuService
	{ get { return _menuService; } }

	[SupplyParameterFromQuery(Name = "menuid")]
	public long menuid { get; set; }

	[Parameter]
	public string TabTitle { get; set; } = "字典管理";

	[Parameter]
	public string TabIcon { get; set; } = "home";

	public RenderFragment GetPageTitle() =>
	@<div>
	<Icon Type="@TabIcon" /> @TabTitle
</div>
	;
	#endregion

	[CascadingParameter]
	public Error? Error { get; set; }

	protected override async Task OnInitializedAsync()
	{
		try
		{
			baseRender = new BaseRenderFragment();

			await InitSelectData();
			await InitSeachMain();
			await InitModal();
			await Refresh(false);
			await MeTab.InitTabTitle();

		}
		catch (Exception ex)
		{
			Error?.ProcessError(ex);
		}

	}
	async Task InitSelectData()
	{
		selectedRows = new List<SysDictType>();
		selectedRowsChild = new List<SysDictData>();

		await Task.CompletedTask;
	}
	async Task InitSeachMain()
	{
		searchModel = new SysDictType();
		await Task.CompletedTask;
	}

	async Task InitModal()
	{
		InitDictTypeEditModal();
		InitDictDataEditModal();

		await Task.CompletedTask;
	}
	void ReSet()
	{
		searchModel = new SysDictType();
	}
	async Task Refresh(bool notice = true)
	{
		await OnSearch(pageargs);
		if (isOnRowExpand)
		{
			table?.CollapseAll();
			isOnRowExpand = false;
		}
		if (notice)
		{
			_ = _message.SuccessAsync("刷新成功!");
		}
	}

	public async Task OnSearch(PaginationEventArgs args)
	{
		tableLoading = true;
		pageargs.Page = args.Page;
		pageargs.PageSize = args.PageSize;

		var page = new PageBaseInput() { Page = pageargs.Page, PageSize = pageargs.PageSize };
		Expression<Func<SysDictType, object>> orderbyfunc = a => a.Id;

		List<(bool, Expression<Func<SysDictType, bool>>)> whereIf = new List<(bool, Expression<Func<SysDictType, bool>>)>();

		Expression<Func<SysDictType, bool>> whereIffunc1 = a => a.Name.Contains(searchModel.Name);

		whereIf.Add((searchModel.Name.IsNotNullOrWhiteSpace(), whereIffunc1));

		pageData = await dataService.GetPage(page, whereIf, orderbyfunc, false);

		InitPageData();

		tableLoading = false;
	}

	void InitPageData()
	{

		dictDataEditModal.PageData = pageData;
		dictTypeEditModal.PageData = pageData;
	}

	private async void OnRowClick(RowData<SysDictType> data)
	{
		var row = data.Data;
		await QueryChildList(row.Id);
	}

	private async void OnRowExpand(RowData<SysDictType> data)
	{
		isOnRowExpand = true;
		data.Data.Children = await QueryChildList(data.Data.Id);
		StateHasChanged();
	}

	public async Task<List<SysDictData>> QueryChildList(long ParentId)
	{
		Expression<Func<SysDictData, bool>> func = a => a.DictTypeId == ParentId;
		Expression<Func<SysDictData, object>> orderbyfunc = a => a.Id;

		return await dataChildService.GetList(func, orderbyfunc, false);
	}

	void Message(string msg = "查询成功")
	{
		_ = _message.SuccessAsync(msg);
	}

}
